import { useEffect, useRef, useState, useCallback } from "react";
import SEO from "components/Common/SEO";
import Footer from "components/Footer/Footer";
import Button from "components/Button/Button";
import { t } from "@lingui/macro";
import { getPageTitle } from "lib/legacy";
import "./Airdrop.scss";
import { ethers } from "ethers";
import { useChainId } from "lib/chains";
import { Icon1, Icon2, PointsTask, Cup } from "img/airdrop/icon";
import { PRICE_DECIMALS } from "./useAridrop";
import useWallet from "lib/wallets/useWallet";
import AirdropAbi from "abis/AirdropReward-abi.json";
import { contractFetcher, callContract } from "lib/contracts";
import { getIPFS, getMerkleTreeValueByAccount } from "./AirdropCheck/useAirdropCheck";
import { ARBITRUM, ARBITRUM_GOERLI } from "config/chains";
import { getContract } from "config/contracts";
import cx from "classnames";
import PointsCard from "./components/PointsCard"
import { useAccountPoints } from "./useAridrop";
import PointsDetail from "./components/PointsDetail"
import PointsDashboard from "./components/PointsDashboard"
import HistoryPointsModal from "./components/historyPoints";
import { isDevelopment } from "config/env";

export default function Airdrop() {
  const { account: active, signer } = useWallet();
  const rewardId = 1;
  // const airdropData = useAirdropData();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [claimValue, setClaimValue] = useState<string>("");
  const { chainId } = useChainId();
  // const [isAirdrop, setIsAirdrop] = useState<boolean>(false);
  const claimProof = useRef<any>(null);
  const [isHistoryPointsVisible, setIsHistoryPointsVisible] = useState<boolean>(false);
  const [isClaimed, setIsClaimed] = useState<boolean>(false);
  const epoch = useRef<any>(null);

  // TODO: ?
  const chain = isDevelopment() ? ARBITRUM_GOERLI : ARBITRUM;
  const address = getContract(chain, "Airdrop");
  let { data: pointData } = useAccountPoints({
    account: active?.toLocaleLowerCase()
  });
  const [pointsInfo, setPointsInfo] = useState<any>({})
  useEffect(() => {
    setPointsInfo(pointData)
  }, [pointData]);
  // const [tableActive, setTableActive] = useState<number>(0)
  const floorStringNumber = (strNum, ratio = 1, precision = PRICE_DECIMALS) => {
    if (precision) {
      strNum = ethers.formatUnits(strNum, precision);
    }
    strNum = strNum * ratio;
    let num = Math.floor(parseFloat(strNum) * 100) / 100;
    if (num < 0) return "0";
    if (num % 1 === 0) {
      return num.toFixed(0);
    } else {
      return num.toFixed(2);
    }
  };

  const getIsClaimed = useCallback(() => {
    try {
      const contractInfo = { abi: AirdropAbi, address: address };
      const getInfo = contractFetcher(undefined, contractInfo);
      getInfo([active, chainId, address, "claims", active, rewardId, epoch.current])
        .then(
          (res: any) => {
            let value = res?.amount?.toString() || "0";
            if (value && value !== "0") {
              setIsClaimed(true);
            } else {
              setIsClaimed(false);
            }
          }
        )
        .catch((error) => {
          // eslint-disable-next-line no-console
          console.log("[Airdrop getRewardInfo]", error);
        });
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log("[Airdrop getRewardInfo]", error);
    }
  }, [active, address, chainId]);
  const getRewardInfo = useCallback(async () => {
    try {
      const contractInfo = { abi: AirdropAbi, address: address };
      const getInfo = contractFetcher(undefined, contractInfo);
      getInfo([active, chainId, address, "getLastEpochReward", rewardId])
        .then((res: any) => {
          const value = res?.epoch?.toNumber() || 0;
          epoch.current = value;
          // const utcOffset = new Date().getTimezoneOffset();
          // const utcTimestamp = new Date().getTime() - (utcOffset * 60 * 1000);
          // if (value !== 0 && value >= utcTimestamp / 1000) {
          //   setIsAirdrop(true)
          // }
          return getIPFS(res.merklePath);
        })
        .then((data: any) => {
          const record = getMerkleTreeValueByAccount(data, active);
          claimProof.current = record?.proof || null;
          setClaimValue(record?.value || "");
          getIsClaimed();
        })
        .catch((error) => {
          // eslint-disable-next-line no-console
          console.log("[Airdrop getRewardInfo]", error);
        });
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log("[Airdrop getRewardInfo]", error);
    }
  }, [active, address, chainId, getIsClaimed]);
  useEffect(() => {
    getRewardInfo();
  }, [getRewardInfo, active]);
  const claim = async () => {
    setIsSubmitting(true);
    const contract = new ethers.Contract(address, AirdropAbi, signer);
    callContract(chainId, contract, "claimReward", [1, epoch.current, claimValue, claimProof.current], {
      sentMsg: t`Affiliate Rewards Claimed`,
      successMsg: t`Success claimings`,
      failMsg: t`Claiming failed`,
    }).finally(() => {
      setTimeout(() => {
        getIsClaimed();
        setIsSubmitting(false);
      }, 3000)
    });
  };
  const [tabType, setTabType] = useState<string>("points");
  const isEndAirdrop = false;

  return (
    <SEO title={getPageTitle("Points")}>
      <div className="default-container page-layout Airdrop">
        <div className="text-[33px] text-white font-bold leading-[38px]">Earn Points for Airdrop</div>

        <div className="text-[15px] text-[#B7B7BD] font-normal leading-[18px] mt-[15px]">
          Accumulate points by completing tasks for esMOX Airdrop at Mainnet Launch!
          <a href="https://mirror.xyz/0xc66675b562c139c93e73f31b9aE9e7787bC34Dd7/twVCqr9853keX1H1M0RLQBPTO9oE-6z5N4_EwcRfoos" className="read-more pl-[3px]" target="_blank" rel="noreferrer">
            Learn more
          </a>
        </div>

        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mt-[30px] mb-[20px]">
          <div className="flex flex-row items-center">
            <div
              className="pointBox"
              // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop
              style={{ color: "#dffe00", backgroundImage: `url(${require("../../img/airdrop/arrow.png")})` }}
            >
              <Icon1 color="#dffe00" />
              <span className="ml-[10px]">Collect Points</span>
            </div>
            {
              isEndAirdrop ? (
                <div
                  className="pointBox ml-[10px]"
                  // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop
                  style={{ color: "#dffe00", backgroundImage: `url(${require("../../img/airdrop/arrow.png")})` }}
                >
                  <Icon2 color="#dffe00" />
                  <span className="ml-[10px]">Claim Airdrops</span>
                </div>
              ) : (
                <div
                  className="pointBox ml-[10px]"
                  // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop
                  style={{ color: "#dffe00", backgroundImage: `url(${require("../../img/airdrop/arrow2.png")})` }}
                >
                  <Icon2 color="#9e9e9e" />
                  <span className="ml-[10px] text-[#9e9e9e]">Claim Airdrops</span>
                </div>
              )
            }
          </div>
          {active && isEndAirdrop && (
            <Button
              className="w-full mt-[20px] sm:mt-0 sm:w-[unset] sm:min-w-[206px] !rounded-[8px] h-[40px]"
              variant="primary-action"
              onClick={claim}
              disabled={isSubmitting || isClaimed || !claimValue || !Number(claimValue)}
            >
              {isClaimed
                ? "Claimed"
                : isSubmitting
                  ? t`Claiming...`
                  : t`Claim: ${floorStringNumber(claimValue || 0, 1, 18)} esMOX`}
            </Button>
          )}
        </div>
        <HistoryPointsModal pointsInfo={pointsInfo} isHistoryPointsVisible={isHistoryPointsVisible} setIsHistoryPointsVisible={setIsHistoryPointsVisible} />

        <PointsDashboard pageData={pointsInfo?.airdrop || {}} />
        <PointsDetail pageData={pointsInfo?.airdrop || {}} />

        <div className="flex gap-[20px] mb-[20px] cursor-pointer points-tabs">
          <div className={cx("font-[16px] points-pd flex gap-[6px] items-center points-tab", { "points--active": tabType === 'points' })} onClick={() => setTabType('points')}>
            <PointsTask color={tabType === 'points' ? '#dffe00' : '#858B85'} />
            Point Tasks
          </div>
          <div className={cx("points-tab font-[16px] points-pd flex gap-[6px] items-center", { "points--active": tabType === 'leaderboard' })} onClick={() => setTabType('leaderboard')}>
            <Cup color={tabType === 'leaderboard' ? '#dffe00' : '#858B85'} />
            Leaderboard
          </div>
        </div>

        <PointsCard />

        {/* {
          tabType === 'points' ? <PointsCard /> : (
            <div className="TradingProfit newTable">
              <Leaderboard />
            </div>
          )
        } */}
      </div>
      <Footer />
    </SEO>
  );
}
